﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO.Ports;

namespace GerPlayHouse
{
    class ConexaoSerial
    {
        private static ConexaoSerial instance;
        private SerialPort port;

        private ConexaoSerial() {
            port = new SerialPort("COM3", 9600, Parity.None, 8, StopBits.One);
            try
            {
                port.Open();
            }
            catch (Exception e) {
                throw e;
            }
        }

        public static ConexaoSerial Instance
        {
            get
            {
                if (instance == null)
                {
                    instance = new ConexaoSerial();
                }
                return instance;
            }
        }

        public void enviarStringPorta(string texto) {
            if (port.IsOpen)
            {
                port.Write(texto);
            }
            else
            {
                throw new NotOpenConexaoException();
            }
        }

        public string obterStringPorta()
        {
            string retorno = "";
            try
            {
                if (port.IsOpen)
                {
                    retorno = port.ReadLine();
                }
            }
            catch (InvalidOperationException e){
                Console.WriteLine(e.Message);
            }
            catch (TimeoutException e) {
                Console.WriteLine(e.Message);
            }
            return retorno;
        }

        public void fecharPorta() {
            if (port.IsOpen)
            {
                port.Close();
            }
            else
            {
                throw new NotOpenConexaoException();
            }
        }
    }

    
}
